package com.dems.admin.controller;

import com.dems.core.util.SCaptcha;
import com.dems.domain.JsonResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录登出控制器
 */
@RestController
public class LogInOutController {

    @GetMapping(value = "/logout")
    public JsonResponse logoutPage(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return JsonResponse.success();
        //You can redirect wherever you want, but generally it's a good practice to show login screen again.
    }

    /**
     * @author jiaqing.xu@hand-china.com
     * @date 2017/8/23
     * @description 生成图片验证码
     */
    @RequestMapping(value = "/login/vcode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void verification(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {

        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setPath("/");
        cookie.setMaxAge(3600);
        response.addCookie(cookie);

        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers");
        response.setHeader("Access-Control-Allow-Credentials", "true");  //关键设置
        response.setHeader("XDomainRequestAllowed","1");

        response.setDateHeader("Expires", 0);
        //实例生成验证码对象
        SCaptcha instance = new SCaptcha();
        //将验证码存入session
        session.setAttribute("vcode", instance.getCode());
        //向页面输出验证码图片
        instance.write(response.getOutputStream());
    }

}
